<template>
  <a-select
    v-model="selectedId"
    :multiple="multiple"
    allow-search
    placeholder="请选择人员"
    :allow-clear="!isRequired"
    @change="handleChangeSelector"
  >
    <a-option v-for="item in list" :key="item.id" :value="item.id"
      >{{ item.name }}
    </a-option>
  </a-select>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { queryPolicyList, PolicyParams, PersonVo } from '../../api/person';

  const props = defineProps({
    isRequired: {
      type: Boolean,
      default() {
        return false;
      },
    },
    value: { type: String },
    multiple: { type: Boolean, default: false },
  });
  const selectedId = ref(props.value);
  const list = ref<PersonVo[]>([]);
  const emit = defineEmits(['handleChangeSelector']);

  const generateFormModel = () => {
    return {
      name: '',
      phone: '',
      page: 1,
      rows: 9999,
    };
  };
  const formModel = ref(generateFormModel());
  const fetchList = async (params: PolicyParams) => {
    try {
      const { data } = await queryPolicyList(params);
      list.value = data.rows;
    } catch (err) {
      // you can report use errorHandler or other
    }
  };
  const handleChangeSelector = (v: any) => {
    emit(
      'handleChangeSelector',
      v,
      props.multiple
        ? list.value.filter((item: any) => v.includes(item.id))
        : list.value.find((item: any) => item.id === v)
    );
  };

  fetchList(formModel.value);

  defineExpose({ handleChangeSelector });
</script>
